package com.hyzh.latte.sand.socket;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.coffee.socketio.handler.SocketioConnectHandler;
import com.corundumstudio.socketio.SocketIOClient;
import com.hyzh.latte.sand.SandClient;
import com.hyzh.latte.sand.SandClientTypeEnum;
import com.hyzh.latte.sand.SandSessionManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @author: songkui
 * @since: 2024/3/21 0:14
 */
@Service
@Slf4j
public class SandSocketConnectHandler implements SocketioConnectHandler {


    @Override
    public void connect(Map<String, List<String>> params, SocketIOClient client) {
        log.info("******* Sand connect: session {}; params {} ",  client.getSessionId(), JSON.toJSONString(params));
        List<String> userIdList = params.get("userId");
        List<String> typeList = params.get("stype"); //PC  MT
        List<String> parkList = params.get("park");

        if (CollectionUtil.isEmpty(parkList) || CollectionUtil.isEmpty(typeList) || CollectionUtil.isEmpty(userIdList)){
            log.error("Sand connect failure:  please required parameter ");
            return;
        }

        String userId =  userIdList.get(0);
        String clientType = typeList.get(0);
        String park = parkList.get(0);

        SandClientTypeEnum typeEnum = SandClientTypeEnum.valueOfCode(clientType);
        if (null == typeEnum){
            log.error("Sand connect failure: clientType error [type: {}]", clientType);
            client.disconnect();
            return;
        }

        SandClient sandClient = new SandClient();

        sandClient.setClient(client);
        sandClient.setSessionId(client.getSessionId().toString());
        sandClient.setUserId(userId);
        sandClient.setTypeEnum(typeEnum);
        sandClient.setParkCode(park);

        if (SandClientTypeEnum.MT.equals(typeEnum)){
            SandSessionManager.getInstance().putMt(sandClient);
        }else {
            SandSessionManager.getInstance().putPcMap(sandClient);
        }

    }
}
